# figure_2.R

rm(list = ls())
setwd("/Users/John/Dropbox/")

# --- Load Packages ---
library(readxl)
library(readr)
library(tidyverse)
library(ggplot2)
library(cowplot)

# --- Load and reshape datasets ---
or <- read_excel("JOP_Replication_Materials/data/raw/dv_clean.xlsx", sheet = "ownership_restrictions") %>%
  pivot_longer(cols = 7:12, values_to = "isic")

lcr <- read_excel("JOP_Replication_Materials/data/raw/dv_clean.xlsx", sheet = "local_content_requirements") %>%
  pivot_longer(cols = 7:13, values_to = "isic")

gp <- read_excel("JOP_Replication_Materials/data/raw/dv_clean.xlsx", sheet = "government_procurement") %>%
  pivot_longer(cols = 7:11, values_to = "isic")

# --- Combine and process --- 
combined <- bind_rows(or, lcr, gp) %>%
  filter(!is.na(isic)) %>%
  group_by(isic, year) %>%
  mutate(isic_year = n()) %>%
  group_by(type, year) %>%
  mutate(type_year = length(unique(desc_chinese))) %>%
  ungroup()

# --- Clean and label ---
df <- combined %>%
  dplyr::select(year, desc_chinese, type, type_year) %>%
  distinct(year, type, .keep_all = TRUE) %>%
  mutate(
    Type = case_when(
      type == 1 ~ "FDI Ownership Restrictions",
      type == 2 ~ "Local Content Requirements",
      type == 3 ~ "Government Procurement"
    ),
    Type = factor(Type, levels = c("Government Procurement", 
                                   "FDI Ownership Restrictions", 
                                   "Local Content Requirements"))
  ) %>%
  filter(year >= 1995 & year <= 2015) %>%
  arrange(year, type)

# Define color-blind-friendly palette
cb_palette <- c(
  "Government Procurement" = "grey70",
  "FDI Ownership Restrictions" = "grey40",
  "Local Content Requirements" = "black"
)

# --- Plot --- 
fig2 <- ggplot(df, aes(x = year, y = type_year, fill = Type)) + 
  geom_bar(position = "stack", stat = "identity", width = 1) + 
  scale_fill_manual(values = cb_palette) +
  labs(
    title = "Technology Absorption Policies in Place, 1995–2015",
    y = "Yearly Total",
    x = "Year"
  ) + 
  theme_bw(base_size = 14) +
  theme(
    plot.title = element_text(hjust = 0.5),
    axis.title = element_text(size = 14),
    axis.text = element_text(size = 12),
    legend.title = element_text(size = 14),
    legend.text = element_text(size = 12)
  )

# Save PDF (with adjusted height to reduce vertical footprint)
ggsave(
  filename = "JOP_Replication_Materials/output/figures/figure_2.pdf",
  plot = fig2,
  width = 8.5, height = 5.5  # default width, reduced height
)

# --- Save figure --- 

message("✅ Saved figure to: JOP_Replication_Materials/output/figures/figure_2.pdf")
browseURL("JOP_Replication_Materials/output/figures/figure_2.pdf")
